package com.csxy.news.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csxy.news.bean.User;
import com.csxy.news.service.LoginService;
import com.csxy.news.util.WebUtil;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login.servlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//提取请求参数
		String op=request.getParameter(WebUtil.OP);
		if (null==op) {
			//说明是显示登录表单
			
		}else{
			//提取登录参数
			String verifyCode=request.getParameter(WebUtil.VERIFY_CODE);			
			//首选检测验证码是否正确
			boolean b=WebUtil.checkVerifyCode(request, verifyCode);
			if(b){
				String username=request.getParameter(WebUtil.USERNAME);
				String password=request.getParameter(WebUtil.PASSWORD);
				//说明是提交登录表单进行登录处理
				LoginService service=new LoginService();
				User u=service.checkFor(username.trim(), password.trim());
				if(null!=u){
					//登录成功，将用户对象保存到用户级别的上下文对象中（session）
					WebUtil.saveLoginUser(request,u);
					//重定向到管理页
					response.sendRedirect("admin.servlet");
					return;
					
				}	
			}
			
			//登录失败，重新登录
			request.getRequestDispatcher("login.jsp").forward(request, response);
				
		}
	}

}
